import { findFile } from 'pkg-types';
import yaml from 'yaml';
import fs from 'fs/promises';
import { getEvidenceConfig } from './getEvidenceConfig.js';
import { EvidenceError } from '../lib/EvidenceError.js';
import path from 'path';

/**
 * @param {boolean} [update = false]
 * @returns {Promise<string>}
 */
export const createEvidenceConfig = async (update) => {
	const configPath = await findFile('evidence.config.yaml').catch(() =>
		path.join(process.cwd(), 'evidence.config.yaml')
	);

	const existingConfig = await getEvidenceConfig().catch(() => false);

	const config = {
		plugins: {
			components: {},
			datasources: {}
		}
	};

	if (existingConfig) {
		if (!update) {
			throw new EvidenceError(
				'Refusing to create evidence configuration file. Configuration file already exists.',
				'Run this command again with --update to add any missing fields to your existing configuration'
			);
		}
		Object.assign(config, existingConfig);
	}

	const comments = [
		'This file was automatically generated by the Evidence command line',
		'To easily configure Evidence, use `npx evidence config`'
	];

	const content = `# ${comments.join('\n# ')}\n\n${yaml.stringify(config)}`;

	await fs.writeFile(configPath, content);

	return configPath;
};
